from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponse
import django.utils.simplejson as json
from django.contrib.auth.models import User
import Image, ImageFont, ImageDraw, ImageFilter
from django.conf import settings
import glob, random

def captcha(request):
    """ Generate a captcha image. """
    response = HttpResponse()
    
    chars, msg = 'abcdefghkmnpqrstuvwxyz23456789', ''
    for i in range(4):
        msg += chars[random.randint(0, len(chars) - 1)]
    request.session['captcha'] = msg
    
    # get available fonts and backgroup images
    fonts = glob.glob(settings.MEDIA_ROOT + '/fonts/*.ttf')
    bgs = glob.glob(settings.MEDIA_ROOT + '/captcha/*.jpeg')
    
    im = Image.new('RGB', (128, 128))
    font = ImageFont.truetype(fonts[random.randint(0, len(fonts) - 1)], 32)
    bg = Image.open(bgs[random.randint(0, len(bgs) - 1)])
    
    # draw text
    draw = ImageDraw.Draw(im)
    color = (random.randint(128, 255), random.randint(128, 255),
             random.randint(128, 255))
    draw.text((20,40), msg, font = font, fill = color)
    #im = im.rotate(random.randint(-30, 30))
    
    # setup mask image
    def convert_mask(p):
        if p > 0:
            return 0
        else:
            return 255
    mask = im.convert('L').point(convert_mask)
    
    # blend image
    Image.composite(bg, im, mask).save(response, 'jpeg')
    
    del draw, font, im, bg, mask
    
    response['Content-Type'] = 'image/jpeg'
    return response